<?php

require_once('request/AbstractRequest.class.php');


class FetchTopicsRequest extends AbstractRequest {
	
	private $_indent = 0;
	private $_out = '';
	
	protected function internalExecute($requestXml) {
		if($requestXml == null) {
			$requestXml = simplexml_load_string('<Request><User><UserId>1</UserId></User></Request>');
			#throw new Exception("Insufficient post data!");
		}
		
		$this->out('<Topics>');
		$this->fetchOfferedNeededTopics($requestXml, true);
		$this->fetchOfferedNeededTopics($requestXml, false);
		$this->out('</Topics>');
		
		echo $this->_out;
	}
	
	private function fetchOfferedNeededTopics($requestXml, $isOffered) {
		$tagName = $isOffered ? 'OfferedTopics' : 'NeededTopics';
		$this->out('<'.$tagName.'>');
		
		$userId = $requestXml->User->UserId;
		
		$topics = $isOffered ? $this->topicDao->fetchOfferedTopics($userId) :
							 $this->topicDao->fetchNeededTopics($userId);

		foreach($topics as $topic) {
			/*
			$sub_topic_id = $isOffered ? $topic->offeredTopicId : $topic->neededTopicId; #$row[$subTopicIdName];
			$topic_id = $topic->topicId; # $row['topic_id'];
			$title = $topic->title; # $row['title'];
			$vote_cnt = $topic->voteCnt; # $row['vote_cnt'];
			$yet_voted = $topic->yetVoted; # $row['yet_voted'];
			$user_id = $topic->userId; # $row['user_id'];
			$category_id = $isOffered ? $topic->offeredCategoryId : $topic->neededCategoryId; # $row['category_id'];
			
			$this->out('<'.$tagName.' '.$tagName.'Id="' . $sub_topic_id . '" TopicId="' . $topic_id . '">');
			$this->out('<Title>' . wrapCData($title) . '</Title>');
			
			$this->out('<Vote>');
			$this->out('<VoteCnt>' . $vote_cnt . '</VoteCnt>');
			$this->out('<YetVoted>' . $yet_voted . '</YetVoted>');
			$this->out('</Vote>');
			
			$this->out('<User><UserId>' . $user_id . '</UserId></User>');
			$this->out('<CategoryId>' . $category_id . '</CategoryId>');
			
			$this->out('</'.$tagName.'>');
			*/
			$this->out($topic->toXmlString());
		}
		$this->out('</'.$tagName.'>');
	}
	
	private function out($text) {
		$this->_out .= $text . "\n";
	}
	
	/*
	private function out($text) {
		$isTag = (substr($text, 0, 1) == '<') && (substr($text, 0, 9) != '<![CDATA[');
		$isClosingTag = $isTag && (substr($text, 0, 2) == '</');
		
		$tabs = "";
		for($i=0; $i < $this->_indent; $i++) $tabs .= "\t";
		$this->_out .= $tabs;
		
		$this->_out .= $text . "\n";
		
		if($isTag && !$isClosingTag) {
			$this->_indent++;
		} else {
			$this->_indent--;
		}
	}*/
	
}

?>